<template>
  <a-card :bordered="false" :title="modalTitle" v-if="visible">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right">
          <a-popconfirm
            v-if="!viewFlag"
            title="询价完成操作过后将无法更改，确认进行该操作吗？"
            @confirm="save(DictCache.VALUE.PURCHASE_ORDER_STATUS.PURCHASE_ORDER_STATUS_DQHT)">
            <a-button type="danger">提交主管确认</a-button>
          </a-popconfirm>
          <a-button style="margin-left: 8px" type="primary" @click="save()" v-if="!viewFlag">保存</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>
    <title-divider title="基本信息" width="90px"></title-divider>
    <detail-list title="" :col="3">
      <detail-list-item term="单号">{{ record.billNo }}</detail-list-item>
      <detail-list-item term="公司名称">{{ record.companyName }}</detail-list-item>
      <detail-list-item term="项目名称">{{ record.projectName }}</detail-list-item>
      <detail-list-item term="项目记账主币">{{ moneyTypeMap[record.projectMoneyType] }}</detail-list-item>
      <detail-list-item term="类型">{{ BaseTool.Object.getField(typeMap,record.type) }}</detail-list-item>
      <detail-list-item term="需求日期">{{ record.demandDate }}</detail-list-item>
      <detail-list-item term="预计总金额">{{ BaseTool.Amount.formatter(record.originMoney) }}</detail-list-item>
      <detail-list-item term="实际总金额">{{ BaseTool.Amount.formatter(record.money) }} {{ moneyTypeMap[record.moneyType] }}</detail-list-item>
      <detail-list-item term="数量">{{ record.quantity }}</detail-list-item>
      <detail-list-item term="采购员">{{ record.purchaserName }}</detail-list-item>
      <detail-list-item term="状态"><badge :status="DictCache.COLOR.PURCHASE_ORDER_STATUS[record.status]" :text="statusMap[record.status]"></badge></detail-list-item>
    </detail-list>
    <title-divider title="询价信息" width="100px"></title-divider>
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>

      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">

          <a-form-item
            label="币种"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              @change="changeMoneyType"
              :disabled="viewFlag"
              v-decorator="['moneyType', { rules: [{required: true, message: '币种不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in userMoneyTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="汇率"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              :disabled="viewFlag"
              style="width: 100%"
              :min="0"
              :step="0.01"
              v-decorator="['exchangeRate', {rules: [{required: true, message: '汇率不能为空'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="供货周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              :disabled="viewFlag"
              type="number"
              suffix="天"
              v-decorator="['supplyPeriod', {rules: [{required: true, message: '供货周期不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">

          <a-form-item
            label="货款支付方式"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['payType',{initialValue: 1}]"
              :disabled="viewFlag"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in payTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="发票类别"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['invoiceType',{initialValue: 1}]"
              :disabled="viewFlag"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in invoiceTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <purchase-order-list :view-flag="viewFlag" ref="orderList" @ok="updateMoney" :viewFlag="viewFlag" v-show="flag"/>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { enquiryPurchaseOrder } from '@/api/purchase/purchase-order'
import { querySysConfig } from '@/api/upms/config'
import PurchaseOrderList from './PurchaseOrderList'
import DetailList from '@/components/tools/DetailList'
const DetailListItem = DetailList.Item

export default {
  name: 'BasePurchaseOrder',
  components: {
    PurchaseOrderList,
    DetailList,
    DetailListItem
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      record: {},
      flag: false,
      rateMap: {},
      viewFlag: false,
      // 下拉框map
      typeMap: {},
      statusMap: {},
      payTypeMap: {},
      invoiceTypeMap: {},
      moneyTypeMap: {},
      userMoneyTypeMap: {},
      users: []

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_APPLY_TYPE)
    this.payTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_PAY_TYPE)
    this.invoiceTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_INVOICE_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_ORDER_STATUS)
    this.moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    const newMap = {}
    const moneyTypes = this.$store.getters.userInfo.moneyTypes
    for (let i = 0; i < moneyTypes.length; i++) {
      const value = moneyTypes[i]
      newMap[value] = this.moneyTypeMap[value]
    }
    this.userMoneyTypeMap = newMap
    const rateMap = {}
    querySysConfig({}).then(res => {
      res.data.forEach((item) => {
        rateMap[item.code] = item.content
      })
      this.rateMap = rateMap
    })
  },
  methods: {
    base (record) {
      this.BaseTool.ListForm.clearOneList(this)
      this.record = record
      this.visible = true
      this.viewFlag = !(this.record.status === this.DictCache.VALUE.PURCHASE_ORDER_STATUS.PURCHASE_ORDER_STATUS_DXJ)
      this.flag = true
      const { form: { setFieldsValue } } = this
      this.$store.dispatch('setChangeFlag', false)
      this.modalTitle = '采购询价'
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'supplyPeriod',
          'payType',
          'moneyType',
          'exchangeRate',
          'invoiceType'
        ])))
        this.$store.dispatch('setMoneyType', record.moneyType)
        this.$store.dispatch('setExchangeRate', record.exchangeRate)
        const modal = this.$refs.orderList
        modal.base(record)
      })
    },
    changeMoneyType (value) {
      const { form: { setFieldsValue } } = this
      let rate = 1
      if (this.record.projectMoneyType !== value) {
        rate = this.rateMap[this.DictCache.TYPE.MONEY_TYPE + value + '_' + this.record.projectMoneyType] || this.rateMap[this.DictCache.TYPE.MONEY_TYPE + this.record.projectMoneyType + '_' + value]
      }
      setFieldsValue({
        exchangeRate: rate
      })
      this.$store.dispatch('setMoneyType', value)
      this.$store.dispatch('setExchangeRate', rate)
      this.$store.dispatch('setChangeFlag', value !== this.record.moneyType)
    },
    save (value) {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.submitType = value
        // 日期处理
        values.demandDate = this.BaseTool.Date.formatter(values.demandDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.BaseTool.ListForm.setOneListValues(this, values)
        enquiryPurchaseOrder(values)
          .then(() => {
            this.handleCancel(values)
          }).catch(() => {
            this.confirmLoading = false
          })
      })
    },
    handleCancel (values) {
      this.visible = false
      this.flag = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    },
    updateMoney (money) {
      this.record.money = money
    }

  }
}
</script>
